package com.svs.common.utils.data;

import java.text.MessageFormat;
import java.util.HashMap;

import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;
import com.svs.common.utils.data.entity.DBLink;
import com.svs.common.utils.data.entity.DbType;

public class JDBCTemplateUtil {

	public static HashMap<String, JdbcTemplate> templateMap = new HashMap<String, JdbcTemplate>();
	public static final int INITIALSIZE = 10;
	public static final int MAXACTIVE = 60;
	public static final int CONNECTION_TIME_OUT = 7200;

	public static JdbcTemplate createJDBCTemplate(DBLink link) {

		JdbcTemplate template = templateMap.get(link.getTemplateName());
		if (null != template) {
			return template;
		}
		String jdbcUrl = link.getSourceType().urlFormat();
		jdbcUrl = MessageFormat.format(jdbcUrl, link.getHostName(), link.getPort() + "", link.getDbName());

		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(link.getSourceType().getDriver());
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(link.getUsername());
		dataSource.setPassword(link.getPassword());
		dataSource.setInitialSize(INITIALSIZE);
		dataSource.setMaxActive(MAXACTIVE);
		if (link.getSourceType().equals(DbType.MySQL)) {
			dataSource.setTestWhileIdle(true);
			dataSource.setValidationQuery("select 1");
			dataSource.setTimeBetweenEvictionRunsMillis(300000);
			dataSource.setMinEvictableIdleTimeMillis(3600000);
		}
		template = new JdbcTemplate(dataSource);
		templateMap.put(link.getDbName(), template);
		return template;
	}

	public static JdbcTemplate getJdbcTemplate(String templateName) {
		return templateMap.get(templateName);
	}
}
